<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- icon -->

    <link
      rel="shortcut icon"
      href="https://images.cy-zq.cn/logo/Google/cy11.png"
      type="image/x-icon"
    />
    <title>CY</title>
    <!-- Google tag (gtag.js) -->
    <script
      async
      src="https://www.googletagmanager.com/gtag/js?id=G-FQJ1Q67QZY"
    ></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag() {
        dataLayer.push(arguments);
      }
      gtag("js", new Date());

      gtag("config", "G-FQJ1Q67QZY", {
        page_path: window.location.pathname,
        page_location: window.location.href,
        page_title: document.title,
      });

      // 添加页面加载完成事件
      window.addEventListener("load", function () {
        gtag("event", "page_view");
      });
    </script>
    <!-- End Google Analytics -->

    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/github-markdown-css/github-markdown.css"
    />

    <script src="https://cdn.jsdelivr.net/npm/markdown-it@13.0.1/dist/markdown-it.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it-footnote/3.0.3/markdown-it-footnote.min.js"></script>

    <style>
      .markdown-body {
        box-sizing: border-box;
        min-width: 200px;
        max-width: 980px;
        margin: 0 auto;
        padding: 45px;
      }

      .markdown-body hr {
        border: none;
      }

      .status {
        position: fixed;
        top: 10px;
        right: 22px;
        z-index: 1001;
        padding: 10px;
        font-size: 14px;
        background: #f0f0f0;
        border-radius: 5px;
      }

      .input-container {
        position: fixed;
        bottom: 10px;
        left: 50%;
        z-index: 1000;
        width: 100vw;
        text-align: center;
        background: white;
        transform: translateX(-50%);
      }

      #input-container #input {
        background: rgb(243 244 246);
        resize: none;
      }

      #send {
        position: absolute;
        right: calc(50% - 35vw);
        bottom: 10px;
        width: 40px;
        border-radius: 5px;
        cursor: pointer;
      }

      .title {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 1000;
        width: 100vw;
        padding: 12px;
        font-weight: 600;
        font-weight: 600;
        font-size: 16px;
        text-align: center;
        background: white;
      }
    </style>
  </head>

  <body>
    Ï
    <div class="title"></div>
    <div class="status" id="status"></div>
    <div class="input-container" id="input-container">
      <textarea
        id="input"
        placeholder="请输入问题"
        rows="2"
        style="
          width: 70vw;
          height: 70px;
          border: 1px solid #ccc;
          border-radius: 15px;
          padding: 8px;
        "
      ></textarea>
      <img
        id="send"
        src="https://chaoyang-oss.oss-cn-hangzhou.aliyuncs.com/%E5%8F%91%E9%80%81.png"
        alt=""
        onclick="fetchDeepseekStream(); "
      />
    </div>
    <div
      class="chat-container"
      style="height: calc(100vh - 130px); overflow-y: auto; position: relative"
    >
      <div id="output" class="markdown-body"></div>
    </div>

    <script>
      const md = window.markdownit().use(window.markdownitFootnote);
      let isUserScrolling = false;
      let autoScrollEnabled = true;

      const chatContainer = document.querySelector(".chat-container");

      // 自动滚动到底部
      function scrollToBottom() {
        if (autoScrollEnabled && !isUserScrolling) {
          chatContainer.scrollTop = chatContainer.scrollHeight;
        }
      }

      // 监听用户滚动
      chatContainer.addEventListener("scroll", () => {
        const { scrollTop, scrollHeight, clientHeight } = chatContainer;
        isUserScrolling = scrollTop + clientHeight < scrollHeight - 30;
      });

      // 监听内容变化
      const observer = new MutationObserver(scrollToBottom);
      observer.observe(chatContainer, {
        childList: true,
        subtree: true,
      });

      // 重新启用自动滚动
      chatContainer.addEventListener("wheel", () => {
        const { scrollTop, scrollHeight, clientHeight } = chatContainer;
        if (scrollTop + clientHeight >= scrollHeight - 30) {
          autoScrollEnabled = true;
        }
      });
    </script>
    <script>
      async function fetchDeepseekStream() {
        let question = document.getElementById("input").value;
        // const url = encodeURI('http://localhost:8888/api/openai?quest=前端处理流式数据通常涉及以下几种场景和技术');
        const url = encodeURI(
          "https://server.cy-zq.cn/api/openai?quest=" + question
        );
        // let url1 = `http://localhost:8888/word`;
        document.querySelector(".title").innerHTML = question;
        // 清空输入框，确保用户可以继续输入新的问题
        document.getElementById("input").value = "";
        const outputDiv = document.getElementById("output");
        const statusDiv = document.getElementById("status");
        let markdown = "";
        let startTime = Date.now();
        let charCount = 0;

        statusDiv.innerHTML = "开始请求...";

        try {
          const response = await fetch(url);

          const reader = response.body.getReader();
          const decoder = new TextDecoder("utf-8", { fatal: true });

          while (true) {
            const { value, done } = await reader.read();
            if (done) break;

            const text = decoder.decode(value, { stream: true });
            markdown += text;
            charCount += text.length;

            console.log(markdown);
            outputDiv.innerHTML = md.render(markdown);
            //  marked.parse(markdown);

            const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(1);
            statusDiv.innerHTML = `
                        已用时间：${elapsedTime}秒<br>
                        字符数：${charCount}
                    `;
          }

          const totalTime = ((Date.now() - startTime) / 1000).toFixed(1);
          statusDiv.innerHTML += `<br>完成！总用时：${totalTime}秒`;
        } catch (error) {
          console.error("请求错误:", error);
          statusDiv.innerHTML = "请求出错！";
        }
      }

      const textarea = document.getElementById("input");
      // 监听键盘按下事件
      textarea.addEventListener("keydown", (event) => {
        // 检查是否按下 Enter 键（keyCode 13 或 key 'Enter'）
        if (event.key === "Enter" || event.keyCode === 13) {
          // 阻止默认换行行为（可选）
          event.preventDefault();

          // 获取输入内容
          const text = textarea.value.trim();

          // 如果内容不为空，执行操作
          if (text) {
            // 执行你想要的操作，比如发送请求或处理文本
            fetchDeepseekStream();

            // 清空输入框（可选）
            textarea.value = "";
          }
        }
      });
    </script>
  </body>
</html>
